<?php

/**
* AdminAddGuideFormModule.class.php
*
* Concrete page module responsable for adding/editing guide
*
* @author     Blazej Zieba <b@zieba.info>
* @copyright  2007 konekto.com
* @version    CVS: $Id:$
*/

require_once("framework/PageModule.class.php");
require_once("HTML/QuickForm.php");
require_once("HTML/QuickForm/Renderer/Default.php");
require_once("ValidationRule.php");

// {{{ SlideShowListModule

class AdminAddGuideFormModule extends PageModule 
{
    // {{{ Class operations 
    private $dbh = null;

    // {{{ SlideShowListModule
    /**
    * C'tor
    */
    
    function AdminAddGuideFormModule()
    {
        trigger_error("ENTER AdminAddGuideFormModule::AdminAddGuideFormModule()", E_USER_NOTICE);

        $options = &PEAR::getStaticProperty('CONFIG_INI','DSN');    
        $this->dbh = new PDO($options['dsn_string']);
        $this->dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );    
    }
    // }}}
    // {{{ getContent

    /**
    * Function returns page content
    *
    */

    function getContent()
    {
    
        if (isset($_GET['id']))
        {
            $defaultValues = AdminAddGuideFormModule::getDefaultValue($_GET['id']);
        }

        trigger_error("ENTER AdminAddGuideFormModule::getContent()", E_USER_NOTICE);

        $options = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL');

        $form = new HTML_QuickForm("AddGuideForm", 'post', $options['service_url'].'index.php?cmd=AdminAddGuide');

        $form->setMaxFileSize($options['max_file_size']);

        $form->addElement('hidden','id', isset($_GET['id']) ? $_GET['id'] : null);       

        $form->addElement('text', 'name', _('Nazwa trasy:'), array('size' => 50, 'maxlength' => 255));
        $form->addElement('textarea', 'desc', _('Opis trasy:'), array('rows' => 3, 'cols' => 50));

        if (isset($defaultValues['pic_file']) ? $defaultValues['pic_file'] : null )
        {
            $global = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL');
            $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');
            $form->addElement('static', null,_('Aktualne zdjęcie:'), '<img alt="'.$defaultValues['pic_file'].'" src="'.$global['service_url'].'send_image.php?id='.$defaultValues['pic_file'].'">');
            $form->addElement('checkbox','delete_pic_file', _('Usuń zdjęcie:'));
        }  

        $form->addElement('file', 'pic_file', _('Zdjęcie:'), array()); 

        if (isset($defaultValues['sound_file']) ? $defaultValues['sound_file'] : null )
        {
            $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');
            $form->addElement('static', null,_('Aktualany dźwięk'), '<a href="'.$global['service_url'].'send_sound.php?id='.$defaultValues['sound_file'].'">'._('Pobierz dzwięk').'</a>');
            $form->addElement('checkbox','delete_sound_file', _('Usuń dźwięk:'));
        }  
        $form->addElement('file', 'sound_file', _('Opis dzwiękowy:'), array());

        $form->addElement('submit', 'Submit',_('Zapisz'));


        $form->addRule('name', _('Podaj nazwę'), 'required');
        $form->addRule('id', _('Nieprawidłowa wartość id'), 'NumericOrNull');
        $form->addRule('pic_file',_('Niepoprawny format pliku'),'mymimetype','image/');
        $form->addRule('sound_file',_('Niepoprawny format pliku'),'mymimetype','audio/');
        
        $form->setDefaults(isset($defaultValues) ? $defaultValues : null );
 
        $options = &PEAR::getStaticProperty('CONFIG_INI','TEMPLATES');     
        $statusTpl = new HTML_Template_IT($options["templates_dir"]);
        $statusTpl->loadTemplatefile("status.tpl.xhtml",FALSE,FALSE);
        if ($form->validate()) 
        {
            $data = $form->getSubmitValues(true);

            if ( $form->getSubmitValue( 'id' ) )
            {
                $this->updateGuide($data);
                $statusTpl->setVariable("STATUS",_("Trasa zaktualizowana."));
            }
            else
            {

                $this->addGuide($data);
                $statusTpl->setVariable("STATUS",_("Trasa dodana."));
            }          
         
            return $statusTpl->get();

        }
        else
        {
            $renderer =& new HTML_QuickForm_Renderer_Default($options);
            $renderer -> setFormTemplate(file_get_contents($options["templates_dir"]."form.tpl.xhtml"));
            $renderer -> setElementTemplate(file_get_contents($options["templates_dir"]."formElement.tpl.xhtml"));
            $renderer -> setRequiredNoteTemplate(file_get_contents($options["templates_dir"]."formRequiredNote.tpl.xhtml"));
            $form -> setRequiredNote(_("* pole obowiązkowe")); 
            $form->accept($renderer);

            if (isset($_GET['id']))
            {
                $statusTpl->setVariable("STATUS",_("Edycja trasy"));
            }  
            else
            {
                $statusTpl->setVariable("STATUS",_("Dodaj trasę"));
            } 
        
        
	        return $statusTpl->get().$renderer->toHtml().$statusTpl->get();
        }
    }
    
    // }}}

    // {{{
    /**
    * Process data from form 
    */
    
    public function addGuide($data)
    {

        trigger_error("ENTER AdminAddGuideFormModule::addData()", E_USER_NOTICE);

        if ( ! $this->dbh->beginTransaction() )
        {
            trigger_error("AdminAddGuideFormModule::addGuide()  Could not begin transaction !", E_USER_ERROR);
        }

        //Save data
        $element = array("name","desc");
        $tableKey = array();
        $tableValue = array();
        foreach( $data as $key => $value ) 
        {
            if ( in_array($key,$element) )
            {
                $tableKey[] = $this->dbh->quote($key);
                $tableValue[] = $this->dbh->quote($value);
            }
        } 
        

        $sth = $this->dbh->prepare("INSERT INTO guide (".implode(",",$tableKey).", owner ) VALUES (".implode(",",$tableValue).",:owner)") ;
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> execute();   

        $lastId = $this->dbh->lastInsertId();
        $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');

        $element = array("pic_file","sound_file");
        $tableAssigment = array();

        foreach($data as $key => $value)
        {

            if( in_array($key,$element) )
            {
                if ( move_uploaded_file($value["tmp_name"],$options['upload_dir'].$lastId.$value['name']) )
                {
                    $tableAssigment[] = $this->dbh->quote($key)."=".$this->dbh->quote($lastId.$value['name']);
                }
            }
        }
        if ( count ( $tableAssigment ) )
        {

            $sth = $this->dbh->prepare("UPDATE guide SET ".implode(",",$tableAssigment)." WHERE ROWID = :id AND owner = :owner ") ; 
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id',  $lastId ,PDO::PARAM_INT);
            $sth -> execute();  
        }
   
        if ( ! $this->dbh->commit() )
        {
            trigger_error("AdminAddGuideFormModule::addGuide() Could not end transaction!", E_USER_ERROR);
        }

        //Save to database     
        
    }
    // }}}

    // {{{
    /**
    * Process data from form and update 
    */
    
    public function updateGuide($data)
    {
        
        trigger_error("ENTER AdminAddGuideFormModule::updateGuide()", E_USER_NOTICE);

        if ( ! $this->dbh->beginTransaction() )
        {
            trigger_error("AdminAddGuideFormModule::updateGuide()  Could not begin transaction", E_USER_ERROR);
        }

        $options = &PEAR::getStaticProperty('CONFIG_INI','DSN');    
        //Save data
        $element = array("name","desc");
        $tableAssigment = array();
        foreach( $data as $key => $value ) 
        {
            if ( in_array($key,$element) )
            {
                $tableAssigment[] = $this->dbh->quote($key)."=".$this->dbh->quote($value);
            }
        } 

        $sth = $this->dbh->prepare("UPDATE guide SET ".implode(",",$tableAssigment)."  WHERE ROWID = :id AND owner = :owner") ;
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> bindParam(':id',  $data['id'] ,PDO::PARAM_INT);
        $sth -> execute();  


        $options = &PEAR::getStaticProperty('CONFIG_INI','UPLOAD');

        //Delete uploaded files ?
        if ( isset($data['delete_pic_file']) )
        {
            $sth = $this->dbh->prepare("SELECT pic_file FROM guide WHERE ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id',  $data['id'] ,PDO::PARAM_INT);
            $sth -> execute();  
            $result = $sth->fetch(PDO::FETCH_ASSOC);

            $sth = $this->dbh->prepare("UPDATE guide SET pic_file = null WHERE ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id',  $data['id'] ,PDO::PARAM_INT);
            $sth -> execute();  

            if ( !unlink($options['upload_dir'].$result['pic_file'])  )
            {
                trigger_error("AdminAddGuideFormModule::updateGuide()  Could not remove file ".$options['upload_dir'].$result['pic_file'], E_USER_ERROR);
            }
        }

        if ( isset($data['delete_sound_file']) )
        {
            $sth = $this->dbh->prepare("SELECT sound_file FROM guide WHERE ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id',  $data['id'] ,PDO::PARAM_INT);
            $sth -> execute();  
            $result = $sth->fetch(PDO::FETCH_ASSOC);

            $sth = $this->dbh->prepare("UPDATE guide SET sound_file = null WHERE ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id',  $data['id'] ,PDO::PARAM_INT);
            $sth -> execute();  

            if ( !unlink($options['upload_dir'].$result['sound_file']))
            {
                trigger_error("AdminAddGuideFormModule::updateGuide()  Could not remove file ".$options['upload_dir'].$result['sound_file'], E_USER_ERROR);
            }
        }
        
        

        $element = array("pic_file","sound_file");
        $tableAssigment = array();

        foreach($data as $key => $value)
        {

            if( in_array($key,$element) )
            {
                if ( move_uploaded_file($value["tmp_name"],$options['upload_dir'].$data['id'].$value['name']) )
                {
                    $tableAssigment[] = $this->dbh->quote($key)."=".$this->dbh->quote($data['id'].$value['name']);
                }
            }
        }

        if ( count ( $tableAssigment ) )
        {
            $sth = $this->dbh->prepare("UPDATE guide SET ".implode(",",$tableAssigment)." WHERE ROWID = :id AND owner = :owner") ; 
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
            $sth -> bindParam(':id',  $data['id'] ,PDO::PARAM_INT);
            $sth -> execute(); 
        }



        if ( ! $this->dbh->commit() )
        {
            trigger_error("AdminAddGuideFormModule::updateGuide()  Could not end transaction !", E_USER_ERROR);
        }
        //Save to database     
        
    }
    // }}}

    // {{{ getDefaultValues
    /**
    * getDefaultValues
    */
    
    function getDefaultValue($id)
    {
        trigger_error("ENTER AdminAddGuideFormModule::getDefaultValues()", E_USER_NOTICE);

        $options = &PEAR::getStaticProperty('CONFIG_INI','DSN');    
        $this->dbh = new PDO($options['dsn_string']);
        $this->dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $sth = $this->dbh->prepare("SELECT * FROM guide WHERE ROWID = :id AND owner = :owner ");
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);
        $sth -> bindParam(':id',  $id ,PDO::PARAM_INT);
        $sth -> execute(); 
        $result = $sth->fetch(PDO::FETCH_ASSOC);
        return $result;
    }
    // }}}

    // }}}
}

// }}} 

?>
